package hu.kisszoltan.boxescape;

import hu.kisszoltan.boxescape.gui.GamePane;

import javax.swing.JOptionPane;


public class Game implements Runnable {

	private GamePane gameArea;

	private long startTime = 0;

	private boolean running = false;

	private static Game instance;

	private Game() {
	}

	public static Game getInstance() {
		if (instance == null) {
			instance = new Game();
		}
		return instance;
	}

	public void setGamePane(GamePane gameArea) {
		this.gameArea = gameArea;
		gameArea.reset();
	}

	public static boolean isRunning() {
		return getInstance().running;
	}

	public static int getLevel() {
		return Math
				.round((System.currentTimeMillis() - getInstance().startTime) / 1000);
	}

	public void end() {
		running = false;
		JOptionPane.showMessageDialog(gameArea, "You hold "
				+ (System.currentTimeMillis() - startTime) + " ms.");
		gameArea.reset();
		startTime = 0;
	}

	public void start() {
		if (startTime == 0) {
			running = true;
			startTime = System.currentTimeMillis();
			Thread gameThread = new Thread(getInstance());
			gameThread.start();
		}
	}

	@Override
	public void run() {
		while (running) {
			gameArea.update();
			try {
				Thread.sleep(25);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
